<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Service\File;

class Service
{

    /**
     * 文件上传默认配置
     */
    protected $config = [
            
            // 文件上传临时目录
            'dir' => './Uploads/Picture',
            // 文件临时目录的 web 路径, 未配置时使用 /+$dir 作为默认值
            'path' => '',
            // 允许上传的文件类型,不区分大小写
            'type' => 'jpg,jpeg,png,gif,ico,doc,docx,xls,xlsx,pdf,zip',
            // 文件上传域
            'name' => 'kcs_uploader_file',
            // 模型
            'model' => 'picture'
    ];

    /**
     * 处理文件上传请求
     * 使用 kcs.ploader 前端js组件异步上传时不返回结果, 直接输出 json 数据与js组件交互
     * 使用普通表单同步上传文件时, 返回文件信息
     *
     * 前台使用 js 上传组件需要引入的静态文件
     * <link rel='stylesheet' type='text/css' href='/Public/static/kcs/kcs.css'>
     * <script src='/Public/static/kcs/kcs.src.js'></script>
     * <script src='/Public/static/kcs/kcs.js'></script>
     * <script> KCS.uploader(el,{ type:'image', width:'120', height:'120', url:'{:U('upload')}'}); </script>
     */
    public function upload ($config = array())
    {
        $config = is_array($config) ? array_merge($this->config, $config) : $this->config;
        $msg = Upload::getInstance()->handle($config);
        $msgArr = json_decode($msg, true);
        
        // 上传完毕
        if ($config['model'] and $msgArr['result'])
        {
            $fileInfo = Upload::getInstance()->info;
            
            $fileInfo = array(
                    'name' => $fileInfo['name'],
                    'path' => $fileInfo['path'],
                    'url' => $fileInfo['url'],
                    'md5' => md5_file($fileInfo['path']),
                    'sha1' => sha1_file($fileInfo['path'])
            );
            
            $fileInfo = Model::save($fileInfo, $config);
            $msgArr['result'] = $fileInfo;
            $msg = json_encode($msgArr);
        }
        return $msg;
        // exit($msg);
    }

    /**
     * 保存文件
     * 将临时文件移动到上传目录, 并记录到数据库
     */
    public function save ($webPath, $config)
    {
        $config = is_array($config) ? array_merge($this->config, $config) : $this->config;
        $filePath = Upload::getInstance()->move($webPath, $config);
        return Model::save($filePath, $config);
    }

    /**
     * 处理下载请求
     *
     * @param $type file|content            
     */
    public function download ($fileOrContent, $name, $type = 'file')
    {
        if ($type == 'file')
        {
            if (! file_exists($fileOrContent))
            {
                throw new \Exception('下载文件不存在 : ' . $fileOrContent);
            }
            $size = filesize($fileOrContent);
            $name = $name ?  : basename($fileOrContent);
        }
        else
        {
            $name = $name ?  : 'download';
            $size = strlen($fileOrContent);
        }
        
        $name = preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']) ? rawurlencode($name) : $name;
        
        header("Content-Description: File Transfer");
        header('Content-Length:' . $size);
        header('Content-Disposition: attachment; filename="' . $name . '"');
        
        if ($type == 'file')
        {
            readfile($fileOrContent);
        }
        else
        {
            echo $fileOrContent;
        }
    }

    /**
     * 输出动态文件
     * 如网站图标 favicon.ico
     */
    public function output ()
    {}

    public function downImages($url) {


        $header = array("Connection: Keep-Alive", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Pragma: no-cache", "Accept-Language: zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3", "User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:29.0) Gecko/20100101 Firefox/29.0");

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        //curl_setopt($ch, CURLOPT_HEADER, $v);

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

        curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');

        $content = curl_exec($ch);

        $curlinfo = curl_getinfo($ch);

        //print_r($curlinfo);

        //关闭连接

        curl_close($ch);



        if ($curlinfo['http_code'] == 200) {

            if ($curlinfo['content_type'] == 'image/jpeg') {

                $exf = '.jpg';

            } else if ($curlinfo['content_type'] == 'image/png') {

                $exf = '.png';

            } else if ($curlinfo['content_type'] == 'image/gif') {

                $exf = '.gif';

            }

            //存放图片的路径及图片名称  *****这里注意 你的文件夹是否有创建文件的权限 chomd -R 777 mywenjian

            $filename = date("YmdHis") . uniqid() . $exf;//这里默认是当前文件夹，可以加路径的 可以改为$filepath = '../'.$filename
            $filepath = '/Public/avatar/'.$filename;
            $res = file_put_contents($filepath, $content);
            //$res = file_put_contents($filename, $content);//同样这里就可以改为$res = file_put_contents($filepath, $content);
            //echo $filepath;
            return $res;
        }

    }
}